package com.webserver.controller;

import com.webserver.core.DispatcherServlet;
import com.webserver.entity.Article;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.*;
import java.net.URISyntaxException;

public class ArticleController {
    private static File userDir;
    private static File root;
    private static File staicDir;
static {
    try {
        root = new File(DispatcherServlet.class.getClassLoader().getResource(".").toURI());
        staicDir = new File(root,"static");
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    userDir = new File("./articles");
    if (!userDir.exists()){
        userDir.mkdirs();
    }
}


/**
 * 处理发表文章方法
 */

public void writeArticle(HttpServletResponse response, HttpServletRequest request){
    //获取 标题，作者，发表内容
    String title = request.getParameter("title");
    String author = request.getParameter("author");
    String content = request.getParameter("content");
    System.out.println(title+":"+author+":"+content);
//判断输入是否为null
    if (title==null||author==null||content==null){
        File file = new File(staicDir,"/myweb/article_fail.html");
        response.setContentFile(file);
        return;
    }
    File artcleFile = new File(userDir,title+".obj");

    //序列化把对象存入articles


    try (
        FileOutputStream fos = new FileOutputStream(artcleFile);
        ObjectOutputStream oos = new ObjectOutputStream(fos);){

        //实例化
        Article article = new Article(title,author,content);
        oos.writeObject(article);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    File file = new File(staicDir,"/myweb/article_success.html");
    response.setContentFile(file);

}





















}
